<template>
  <div class="search-bar-container">
    <!-- 搜索栏主体 -->
    <div class="search-bar-wrapper">
      <van-dropdown-menu class="search-dropdown" active-color="#667eea">
        <!-- 地区选择 -->
        <van-dropdown-item 
          ref="areaRef" 
          :title="areaTitle" 
          class="dropdown-item"
        >
          <div class="dropdown-content">
            <!-- 省份选择 -->
            <div class="selection-section">
              <div class="section-header">
                <van-icon name="location-o" class="section-icon" />
                <span class="section-title">选择省份</span>
              </div>
              <div class="options-grid">
                <div
                  v-for="item in provinceList"
                  :key="item.id"
                  class="option-item"
                  :class="{ active: item.id === searchParams.provinceId }"
                  @click="selectProvince(item)"
                >
                  {{ item.name }}
                </div>
              </div>
            </div>

            <!-- 城市选择 -->
            <div class="selection-section" v-if="cityList.length">
              <div class="section-header">
                <van-icon name="cluster-o" class="section-icon" />
                <span class="section-title">选择城市</span>
              </div>
              <div class="options-grid">
                <div
                  v-for="item in cityList"
                  :key="item.id"
                  class="option-item"
                  :class="{ active: item.id === searchParams.cityId }"
                  @click="selectCity(item)"
                >
                  {{ item.name }}
                </div>
              </div>
            </div>

            <!-- 区县选择 -->
            <div class="selection-section" v-if="districtList.length">
              <div class="section-header">
                <van-icon name="home-o" class="section-icon" />
                <span class="section-title">选择区县</span>
              </div>
              <div class="options-grid">
                <div
                  v-for="item in districtList"
                  :key="item.id"
                  class="option-item"
                  :class="{ active: item.id === searchParams.districtId }"
                  @click="selectDistrict(item)"
                >
                  {{ item.name }}
                </div>
              </div>
            </div>
          </div>
        </van-dropdown-item>

        <!-- 价格选择 -->
        <van-dropdown-item 
          ref="priceRef" 
          :title="priceTitle" 
          class="dropdown-item"
        >
          <div class="dropdown-content">
            <div class="selection-section">
              <div class="section-header">
                <van-icon name="gold-coin-o" class="section-icon" />
                <span class="section-title">租金范围</span>
              </div>
              <div class="price-options">
                <div
                  v-for="item in priceList"
                  :key="item.id"
                  class="price-item"
                  :class="{ active: item.id === searchParams.minRent }"
                  @click="selectPrice(item)"
                >
                  <div class="price-label">{{ item.name }}</div>
                  <div class="price-range" v-if="item.minRent || item.maxRent">
                    {{ formatPriceRange(item.minRent, item.maxRent) }}
                  </div>
                </div>
              </div>
            </div>
          </div>
        </van-dropdown-item>
      </van-dropdown-menu>
    </div>

    <!-- 操作按钮区域 -->
    <div class="action-buttons">
      <van-button 
        class="reset-btn" 
        size="small" 
        plain 
        @click="resetFilters"
      >
        <van-icon name="replay" size="14" />
        重置
      </van-button>
      
      <van-button 
        class="search-btn" 
        size="small" 
        type="primary" 
        @click="handleSearch"
      >
        <van-icon name="search" size="14" />
        搜索
      </van-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, ref } from "vue";
import { getProvinceList, getCityList, getDistrictList } from "@/api/search";
import type { AreaInterface, PriceInterface } from "@/api/search/types";
import { showToast } from "vant";

// 组件引用
const areaRef = ref();
const priceRef = ref();

// 数据列表
const provinceList = ref<AreaInterface[]>([]);
const cityList = ref<AreaInterface[]>([]);
const districtList = ref<AreaInterface[]>([]);

// 价格选项
const priceList = ref<PriceInterface[]>([
  { id: 0, name: "不限", minRent: null, maxRent: null },
  { id: 1000, name: "1000元以下", minRent: null, maxRent: 1000 },
  { id: 1001, name: "1000-2000元", minRent: 1000, maxRent: 2000 },
  { id: 2001, name: "2000-3000元", minRent: 2000, maxRent: 3000 },
  { id: 3001, name: "3000-5000元", minRent: 3000, maxRent: 5000 },
  { id: 5001, name: "5000元以上", minRent: 5000, maxRent: null },
]);

// 搜索参数
const searchParams = ref({
  provinceId: null as number | null,
  cityId: null as number | null,
  districtId: null as number | null,
  minRent: null as number | null,
  maxRent: null as number | null,
});

// 选中的名称
const selectedNames = ref({
  province: "",
  city: "",
  district: "",
  price: "",
});

// 计算属性
const areaTitle = computed(() => {
  const { province, city, district } = selectedNames.value;
  if (district) return district;
  if (city) return city;
  if (province) return province;
  return "地区";
});

const priceTitle = computed(() => {
  return selectedNames.value.price || "价格";
});

// 事件定义
const emit = defineEmits<{
  search: [params: typeof searchParams.value];
}>();

// 方法
const loadProvinceList = async () => {
  try {
    const res = await getProvinceList();
    provinceList.value = res.data || [];
  } catch (error) {
    showToast("加载省份列表失败");
  }
};

const selectProvince = async (item: AreaInterface) => {
  searchParams.value.provinceId = item.id;
  searchParams.value.cityId = null;
  searchParams.value.districtId = null;
  selectedNames.value.province = item.name;
  selectedNames.value.city = "";
  selectedNames.value.district = "";
  
  try {
    const res = await getCityList(item.id);
    cityList.value = res.data || [];
    districtList.value = [];
  } catch (error) {
    showToast("加载城市列表失败");
  }
};

const selectCity = async (item: AreaInterface) => {
  searchParams.value.cityId = item.id;
  searchParams.value.districtId = null;
  selectedNames.value.city = item.name;
  selectedNames.value.district = "";
  
  try {
    const res = await getDistrictList(item.id);
    districtList.value = res.data || [];
  } catch (error) {
    showToast("加载区县列表失败");
  }
};

const selectDistrict = (item: AreaInterface) => {
  searchParams.value.districtId = item.id;
  selectedNames.value.district = item.name;
};

const selectPrice = (item: PriceInterface) => {
  searchParams.value.minRent = item.minRent;
  searchParams.value.maxRent = item.maxRent;
  selectedNames.value.price = item.name;
  priceRef.value?.toggle(false);
};

const formatPriceRange = (min: number | null, max: number | null) => {
  if (!min && !max) return "";
  if (!min) return `≤${max}元`;
  if (!max) return `≥${min}元`;
  return `${min}-${max}元`;
};

const resetFilters = () => {
  searchParams.value = {
    provinceId: null,
    cityId: null,
    districtId: null,
    minRent: null,
    maxRent: null,
  };
  selectedNames.value = {
    province: "",
    city: "",
    district: "",
    price: "",
  };
  cityList.value = [];
  districtList.value = [];
  showToast("已重置筛选条件");
};

const handleSearch = () => {
  areaRef.value?.toggle(false);
  priceRef.value?.toggle(false);
  emit("search", searchParams.value);
  showToast("搜索中...");
};

// 生命周期
onMounted(() => {
  loadProvinceList();
});
</script>

<style scoped lang="less">
.search-bar-container {
  background: white;
  border-radius: 16px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  overflow: hidden;
  margin-bottom: 16px;
}

.search-bar-wrapper {
  position: relative;
}

.search-dropdown {
  background: transparent;
  box-shadow: none;
  
  :deep(.van-dropdown-menu__bar) {
    background: white;
    box-shadow: none;
    border-radius: 16px 16px 0 0;
    padding: 0 16px;
    height: 56px;
  }

  :deep(.van-dropdown-menu__item) {
    flex: 1;
    height: 56px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 15px;
    font-weight: 500;
    color: #2c3e50;
    transition: all 0.3s ease;

    &:hover {
      background: rgba(102, 126, 234, 0.05);
    }
  }

  :deep(.van-dropdown-menu__title) {
    display: flex;
    align-items: center;
    gap: 6px;
    
    &::after {
      border-color: #667eea;
      transition: transform 0.3s ease;
    }
  }

  :deep(.van-dropdown-menu__item--active) {
    .van-dropdown-menu__title {
      color: #667eea;
      
      &::after {
        transform: rotate(180deg);
      }
    }
  }
}

.dropdown-content {
  padding: 20px;
  max-height: 60vh;
  overflow-y: auto;
}

.selection-section {
  margin-bottom: 24px;

  &:last-child {
    margin-bottom: 0;
  }
}

.section-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 16px;
  padding-bottom: 8px;
  border-bottom: 1px solid #f0f0f0;
}

.section-icon {
  color: #667eea;
  font-size: 16px;
}

.section-title {
  font-size: 14px;
  font-weight: 600;
  color: #2c3e50;
}

.options-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(80px, 1fr));
  gap: 12px;
}

.option-item {
  padding: 10px 16px;
  background: #f8f9fa;
  border: 1px solid #e9ecef;
  border-radius: 12px;
  text-align: center;
  font-size: 13px;
  color: #495057;
  cursor: pointer;
  transition: all 0.3s ease;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;

  &:hover {
    background: rgba(102, 126, 234, 0.1);
    border-color: #667eea;
    transform: translateY(-1px);
  }

  &.active {
    background: linear-gradient(45deg, #667eea, #764ba2);
    color: white;
    border-color: #667eea;
    box-shadow: 0 2px 8px rgba(102, 126, 234, 0.3);
  }
}

.price-options {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.price-item {
  padding: 16px;
  background: #f8f9fa;
  border: 1px solid #e9ecef;
  border-radius: 12px;
  cursor: pointer;
  transition: all 0.3s ease;

  &:hover {
    background: rgba(102, 126, 234, 0.1);
    border-color: #667eea;
    transform: translateY(-1px);
  }

  &.active {
    background: linear-gradient(45deg, #667eea, #764ba2);
    color: white;
    border-color: #667eea;
    box-shadow: 0 2px 8px rgba(102, 126, 234, 0.3);
  }
}

.price-label {
  font-size: 14px;
  font-weight: 500;
  margin-bottom: 4px;
}

.price-range {
  font-size: 12px;
  opacity: 0.8;
}

.action-buttons {
  display: flex;
  gap: 12px;
  padding: 16px;
  background: #f8f9fa;
  border-top: 1px solid #e9ecef;
}

.reset-btn {
  flex: 1;
  height: 40px;
  border-radius: 12px;
  border-color: #667eea;
  color: #667eea;
  font-weight: 500;
  
  &:hover {
    background: rgba(102, 126, 234, 0.1);
  }
}

.search-btn {
  flex: 2;
  height: 40px;
  border-radius: 12px;
  background: linear-gradient(45deg, #667eea, #764ba2);
  border: none;
  font-weight: 500;
  box-shadow: 0 2px 8px rgba(102, 126, 234, 0.3);
  
  &:hover {
    transform: translateY(-1px);
    box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
  }

  &:active {
    transform: translateY(0);
  }
}

// 响应式设计
@media (max-width: 480px) {
  .dropdown-content {
    padding: 16px;
  }

  .options-grid {
    grid-template-columns: repeat(auto-fill, minmax(70px, 1fr));
    gap: 8px;
  }

  .option-item {
    padding: 8px 12px;
    font-size: 12px;
  }

  .price-item {
    padding: 12px;
  }

  .action-buttons {
    padding: 12px;
    gap: 8px;
  }

  .reset-btn,
  .search-btn {
    height: 36px;
  }
}

// 暗色模式适配
html.dark {
  .search-bar-container {
    background: rgba(28, 28, 30, 0.95);
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.3);
  }

  .search-dropdown {
    :deep(.van-dropdown-menu__bar) {
      background: rgba(28, 28, 30, 0.95);
    }

    :deep(.van-dropdown-menu__item) {
      color: #f5f5f5;

      &:hover {
        background: rgba(102, 126, 234, 0.2);
      }
    }
  }

  .dropdown-content {
    background: rgba(28, 28, 30, 0.95);
  }

  .section-title {
    color: #f5f5f5;
  }

  .section-header {
    border-bottom-color: rgba(255, 255, 255, 0.1);
  }

  .option-item {
    background: rgba(58, 58, 60, 0.8);
    border-color: rgba(255, 255, 255, 0.1);
    color: #f5f5f5;

    &:hover {
      background: rgba(102, 126, 234, 0.3);
    }
  }

  .price-item {
    background: rgba(58, 58, 60, 0.8);
    border-color: rgba(255, 255, 255, 0.1);
    color: #f5f5f5;

    &:hover {
      background: rgba(102, 126, 234, 0.3);
    }
  }

  .action-buttons {
    background: rgba(58, 58, 60, 0.8);
    border-top-color: rgba(255, 255, 255, 0.1);
  }
}
</style>
